﻿<template>
    <view class="app-container">
        <!-- 顶部导航栏 -->
        <view class="nav-bar">
            <view class="back-btn" @click="cancel">返回</view>
            <view class="nav-title">{{ pageTitle }}</view>
            <view class="nav-right">
                <view class="toggle-btn">
                    <view class="toggle-dots">...</view>
                    <view class="toggle-switch">
                        <view class="switch-track">
                            <view class="switch-thumb"></view>
                        </view>
                    </view>
                </view>
            </view>
        </view>

        <!-- 内容区域 -->
        <scroll-view scroll-y class="content">
            <view class="card">
                <!-- 标题输入 -->
                <view class="form-item">
                    <text class="label">标题</text>
                    <input 
                        type="text" 
                        v-model="form.title" 
                        :placeholder="titlePlaceholder" 
                        :disabled="isTitleDisabled"
                        class="input" 
                        :class="{ 'disabled': isTitleDisabled }"
                    />
                </view>
                
                <!-- 内容输入 -->
                <view class="form-item" style="flex-direction: column;align-items: flex-end;">
                    <textarea 
                        v-model="form.content" 
                        :placeholder="contentPlaceholder" 
                        class="textarea"
                        maxlength="2000"
                        auto-height
                    />
                    <text class="char-count">{{ form.content.length }}/2000</text>
                </view>
                
                <!-- 按钮区域 -->
                <view class="buttons-container">
                    <button class="cancel-btn" @click="cancel">取消</button>
                    <button class="delete-btn" @click="deleteNotice" v-if="!isNewContent">删除</button>
                    <button class="confirm-btn" @click="confirm">确定</button>
                </view>
            </view>
        </scroll-view>
    </view>
</template>

<script>
import { useProductStore } from '@/store/product.js';

export default {
    data() {
        return {
            productStore: null,
            editType: '', // 'excluded', 'other', 'riskPrompt', 'custom'
            pageTitle: '新增自定义预订须知',
            isNewContent: true,
            isTitleDisabled: false,
            isEditMode: false,
            editIndex: -1,
            form: {
                title: '',
                content: ''
            }
        };
    },

    computed: {
        titlePlaceholder() {
            if (this.editType === 'excluded') return '费用不含';
            if (this.editType === 'other') return '另付费项目';
            if (this.editType === 'riskPrompt') return '风险提示';
            return '请输入须知标题';
        },
        
        contentPlaceholder() {
            if (this.editType === 'excluded') return '请输入费用不含的内容...';
            if (this.editType === 'other') return '请输入另付费项目的内容...';
            if (this.editType === 'riskPrompt') return '请输入风险提示的内容...';
            return '请输入新的用户须知、提示性内容或格式条款；用户须知等格式条款不得减免经营者法定责任。';
        }
    },

    onLoad(options) {
        // 获取编辑类型
        this.editType = options.type || 'custom';
        this.isNewContent = options.isNew === 'true';
        this.isEditMode = options.isEdit === 'true';
        this.editIndex = options.index ? parseInt(options.index) : -1;
        
        // 初始化 productStore
        this.productStore = useProductStore();
        
        // 设置页面标题和标题禁用状态
        this.setPageConfig();
        
        // 加载现有数据
        this.loadExistingData();
    },

    methods: {
        // 设置页面配置
        setPageConfig() {
            const configMap = {
                'excluded': {
                    title: '编辑费用不含',
                    disabled: true
                },
                'other': {
                    title: '编辑另付费项目',
                    disabled: true
                },
                'riskPrompt': {
                    title: '编辑风险提示',
                    disabled: true
                },
                'custom': {
                    title: '新增自定义预订须知',
                    disabled: false
                },
                'customNotice': {
                    title: '新增自定义预订须知',
                    disabled: false
                }
            };
            
            const config = configMap[this.editType] || configMap['custom'];
            this.pageTitle = config.title;
            this.isTitleDisabled = config.disabled;
        },

        // 加载现有数据
        loadExistingData() {
            if (!this.productStore || !this.productStore.subPageData) {
                this.loadDefaultContent();
                return;
            }

            let data = null;
            switch (this.editType) {
                case 'excluded':
                    data = this.productStore.subPageData.expensesExcluded;
                    break;
                case 'other':
                    data = this.productStore.subPageData.otherExpenses;
                    break;
                case 'riskPrompt':
                    data = this.productStore.subPageData.riskPrompt;
                    break;
                case 'custom':
                case 'customNotice':
                    data = this.productStore.subPageData.customNotices;
                    break;
            }

            if (data) {
                if (this.editType === 'custom' || this.editType === 'customNotice') {
                    // 自定义须知：新增模式清空，编辑模式加载指定项
                    if (this.isEditMode && this.editIndex >= 0) {
                        const editingNotice = uni.getStorageSync('editingCustomNotice');
                        if (editingNotice && editingNotice.notice) {
                            this.form.title = editingNotice.notice.title || '';
                            this.form.content = editingNotice.notice.alt || editingNotice.notice.content || '';
                        } else if (Array.isArray(data) && data[this.editIndex]) {
                            this.form.title = data[this.editIndex].title || '';
                            this.form.content = data[this.editIndex].content || '';
                        } else {
                            this.clearContent();
                        }
                    } else {
                        // 新增模式：避免带入旧数据
                        this.clearContent();
                    }
                } else if (Array.isArray(data) && data.length > 0) {
                    // 兼容数组格式：将数组数据转换为文本
                    this.form.title = data[0].title || '';
                    this.form.content = data.map(item => item.alt || '').join('\n');
                } else if (typeof data === 'string' && data.trim()) {
                    // 兼容字符串格式：直接使用字符串内容
                    this.form.title = this.getDefaultTitle();
                    this.form.content = data;
                } else {
                    this.loadDefaultContent();
                }
            } else {
                this.loadDefaultContent();
            }
        },

        // 获取默认标题
        getDefaultTitle() {
            const titleMap = {
                'excluded': '费用不含',
                'other': '另付费项目',
                'riskPrompt': '风险提示'
            };
            return titleMap[this.editType] || '';
        },

        // 加载默认内容
        loadDefaultContent() {
            const defaultContent = {
                'excluded': {
                    title: '费用不含',
                    content: '1、所属学校/机构提供随队服务或教育附加可能产生的的课时划（所在学校消课），详见订单页面披露。\n2、行程中因营员个人原因造成的设施及设备损坏造成的赔偿需营员承担。'
                },
                'other': {
                    title: '另付费项目',
                    content: '（1）所属学校/机构提供随队服务或教育附加可能产生的的课时划（所在学校消课），详见订单页面披露。\n（2）行程中因营员个人原因造成的设施及设备损坏造成的赔偿需营员承担。'
                },
                'riskPrompt': {
                    title: '风险提示',
                    content: '旅游过程中可能遇到自然灾害、交通延误、健康问题等不可预测因素，导致行程调整或延误。请游客自行购买旅行保险，确保人身和财产安全。旅游活动中需遵守当地法律法规，并服从导游安排。特殊健康状况的游客应提前告知并谨慎选择项目。请妥善保管个人物品，避免丢失或被盗。若因游客个人原因造成的任何损失或事故，旅游公司不承担责任。旅行前请详细了解行程安排与注意事项。'
                },
                'custom': {
                    title: '',
                    content: ''
                }
            };

            const content = defaultContent[this.editType] || defaultContent['custom'];
            this.form.title = content.title;
            this.form.content = content.content;
        },

        // 取消操作
        cancel() {
            uni.navigateBack();
        },
        
        // 删除操作
        deleteNotice() {
            uni.showModal({
                title: '提示',
                content: '确定要删除此内容吗？',
                success: (res) => {
                    if (res.confirm) {
                        this.clearContent();
                        this.saveData();
                        uni.navigateBack();
                    }
                }
            });
        },

        // 清空内容
        clearContent() {
            this.form.title = '';
            this.form.content = '';
        },

        // 确定操作
        confirm() {
            // 表单验证
            if (!this.form.title.trim()) {
                uni.showToast({
                    title: '请输入标题',
                    icon: 'none'
                });
                return;
            }
            
            if (!this.form.content.trim()) {
                uni.showToast({
                    title: '请输入内容',
                    icon: 'none'
                });
                return;
            }
            
            // 保存数据
            this.saveData();
            
            // 返回上一页
            uni.navigateBack();
        },

        // 保存数据
        saveData() {
            console.log('saveData 开始执行');
            console.log('editType:', this.editType);
            console.log('form.title:', this.form.title);
            console.log('form.content:', this.form.content);
            
            if (!this.productStore) {
                this.productStore = useProductStore();
            }
            
            if (!this.productStore.subPageData) {
                this.productStore.subPageData = {};
            }

            // 直接保存字符串内容
            const contentString = this.form.content;

            // 根据编辑类型保存到对应的字段
            console.log('进入 switch 语句，editType:', this.editType);
            switch (this.editType) {
                case 'excluded': {
                    const trimmedContent = contentString.trim();
                    const existingList = Array.isArray(this.productStore.subPageData.expensesExcluded)
                        ? this.productStore.subPageData.expensesExcluded
                        : [];
                    const existing = existingList[0] || {};
                    const item = {
                        title: (this.form.title || '费用不含').trim(),
                        content: trimmedContent,
                        alt: trimmedContent,
                        supplement: existing.supplement || '',
                        order: typeof existing.order === 'number' ? existing.order : 1,
                        isOriginal: existing.hasOwnProperty('isOriginal') ? existing.isOriginal : false
                    };
                    this.productStore.subPageData.expensesExcluded = trimmedContent ? [item] : [];
                    console.log('保存费用不含数据:', item);
                    break;
                }
                case 'other': {
                    const trimmedContent = contentString.trim();
                    const existingList = Array.isArray(this.productStore.subPageData.otherExpenses)
                        ? this.productStore.subPageData.otherExpenses
                        : [];
                    const existing = existingList[0] || {};
                    const item = {
                        title: (this.form.title || '另付费项目').trim(),
                        content: trimmedContent,
                        alt: trimmedContent,
                        supplement: existing.supplement || '',
                        order: typeof existing.order === 'number' ? existing.order : 1,
                        isOriginal: existing.hasOwnProperty('isOriginal') ? existing.isOriginal : false
                    };
                    this.productStore.subPageData.otherExpenses = trimmedContent ? [item] : [];
                    console.log('保存另付费项目数据:', item);
                    break;
                }
                case 'riskPrompt':
                    this.productStore.subPageData.riskPrompt = contentString;
                    console.log('保存风险提示数据:', contentString);
                    break;
                case 'custom':
                case 'customNotice':
                    console.log('进入 custom 分支，editType:', this.editType);
                    // 自定义须知保存到 productStore
                    if (!this.productStore.subPageData.customNotices) {
                        this.productStore.subPageData.customNotices = [];
                    }

                    const newNotice = {
                        title: this.form.title,
                        content: this.form.content,
						alt: this.form.content,
                        id: this.isEditMode && this.editIndex >= 0 ?
                            (this.productStore.subPageData.customNotices[this.editIndex] && this.productStore.subPageData.customNotices[this.editIndex].id) || Date.now() :
                            Date.now()
                    };
                    console.log('创建新须知对象:', newNotice);

                    if (this.isEditMode && this.editIndex >= 0) {
                        // 编辑模式：更新指定索引的须知
                        this.productStore.subPageData.customNotices[this.editIndex] = newNotice;
                        console.log('更新指定索引的自定义须知:', newNotice, '索引:', this.editIndex);
                    } else {
                        // 新增模式：始终新增，不覆盖
                        this.productStore.subPageData.customNotices.push(newNotice);
                        console.log('添加自定义须知:', newNotice);
                    }

                    console.log('保存到 productStore 的自定义须知:', this.productStore.subPageData.customNotices);
                    break;
            }

            console.log('当前 store 数据:', this.productStore.subPageData);
            console.log('customNotices 数据:', this.productStore.subPageData.customNotices);

            // 通知父页面刷新数据
            const pages = getCurrentPages();
            if (pages.length > 1) {
                const prevPage = pages[pages.length - 2];
                if (prevPage && prevPage.$vm) {
                    console.log('通知父页面刷新数据');
                    // 通知上一页刷新数据
                    if (prevPage.$vm.loadDataFromStore) {
                        prevPage.$vm.loadDataFromStore();
                    }
                }
            }

            uni.showToast({
                title: '保存成功',
                icon: 'success'
            });
        }
    }
};
</script>
<style scoped>
.app-container {
    display: flex;
    height: 100vh;
    background: #f8f9fa;
}

/* 顶部导航栏 */
.nav-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 100rpx;
    padding: 0 20rpx;
    background: #fff;
    border-bottom: 1px solid #e0e0e0;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
}

.back-btn {
    font-size: 28rpx;
    color: #333;
    display: flex;
    align-items: center;
}

.back-icon {
    margin-right: 4rpx;
    font-size: 30rpx;
}

.nav-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
}

.nav-right {
    display: flex;
    align-items: center;
}

.toggle-btn {
    display: flex;
    align-items: center;
}

.toggle-dots {
    font-size: 32rpx;
    color: #666;
    margin-right: 10rpx;
}

.toggle-switch {
    display: flex;
    align-items: center;
}

.switch-track {
    width: 60rpx;
    height: 32rpx;
    background: #ddd;
    border-radius: 16rpx;
    position: relative;
}

.switch-thumb {
    position: absolute;
    right: 4rpx;
    top: 4rpx;
    width: 24rpx;
    height: 24rpx;
    background: #999;
    border-radius: 50%;
}

/* 内容区域 */
.content {
    flex: 1;
    padding: 120rpx 20rpx 20rpx;
}

.card {
    background: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.05);
}

.form-item {
	display: flex;
	align-items: center;
    margin-bottom: 20rpx;
	padding-bottom: 20rpx;
	border-bottom: 1rpx solid #eeeeee;
	
}

.label {
	margin-right:20rpx;
	flex-shrink: 0;
    font-size: 30rpx;
    color: #333;
    /* margin-bottom: 12rpx; */
    display: block;
}

.input {
    width: 100%;
    height: 80rpx;
    /* border: 1px solid #e0e0e0; */
    border-radius: 8rpx;
    padding: 0 20rpx;
    font-size: 28rpx;
    box-sizing: border-box;
}

.input.disabled {
    /* background-color: #f5f5f5; */
    color: #999;
    cursor: not-allowed;
}

.textarea {
    width: 100%;
    min-height: 200rpx;
    /* border: 1px solid #e0e0e0; */
    border-radius: 8rpx;
    padding: 20rpx;
    font-size: 28rpx;
    box-sizing: border-box;
    resize: none;
}

.char-count {
    display: block;
    text-align: right;
    font-size: 24rpx;
    color: #999;
    margin-top: 8rpx;
}

/* 按钮容器 */
.buttons-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 40rpx;
}

.buttons-container button {
    font-size: 30rpx;
    height: 72rpx;
    line-height: 48rpx;
    border-radius: 4rpx;
    padding: 12rpx 0;
    flex: 1;
    margin: 0 10rpx;
    box-sizing: border-box;
}

.cancel-btn {
    background: #fff;
    color: #007aff;
    border: 1px solid #007aff;
}

.delete-btn {
    background: #fff;
    color: #ff3b30;
    border: 1px solid #ff3b30;
}

.confirm-btn {
    background: #007aff;
    color: #fff;
    border: none;
}
</style>